package com.mappn.backup.contact;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;
import android.text.TextUtils;

public class ContactProvider extends ContentProvider {

	private static final String TAG = "CloudProvider";

	// shareprefencen中db的名称
	private static final String DB_NAME = "backup.db";
	// 数据库的版本，当版本号大于原来的版本号时会执行Upgrade
	private static final int DB_VERSION = 120;
	// 数据库的包名
	private static final String AUTHORITY = "com.mappn.backup";
	// 表名
	public static final String TABLE_DATA_T = "datat";
	// 表的路径（URI）
	public static final Uri CONTENT_URI_DATA_T = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_DATA_T);


	private static final String PARAMETER_NOTIFY = "notify";

	
	public static final String CONTACT_ID = "_id";
	public static final String CONTACT_NAME = "name";
	public static final String CONTACT_PHONE = "phone";
	public static final String CONTACT_ADDRESS = "address";
	public static final String CONTACT_EMAIL = "email";
	public static final String CONTACT_ORGANIZATION = "organizations";
	public static final String CONTACT_NOTE = "note";
	public static final String CONTACT_NICKNAME = "nikename";

	
	private static class DatabaseHelper extends SDSQLiteOpenHelper {

		public DatabaseHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + TABLE_DATA_T + "(" + CONTACT_ID
					+ " INTEGER PRIMARY KEY AUTOINCREMENT ," + CONTACT_NAME
					+ " TEXT," + CONTACT_PHONE + " TEXT,"
					+ CONTACT_ADDRESS + " TEXT," + CONTACT_EMAIL
					+ " TEXT," + CONTACT_ORGANIZATION + " TEXT,"
					+ CONTACT_NOTE + " TEXT," + CONTACT_NICKNAME
					+ " TEXT);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			if(oldVersion != DB_VERSION){
				db.execSQL("DROP TABLE IF EXITS " + TABLE_DATA_T);
				onCreate(db);
			}
		}

	}
	
	private SDSQLiteOpenHelper mOpenHelper;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = db.delete(args.table, args.where, args.args);
		if(count > 0){
			sendNotify(uri);
		}
		return count;
	}

	private void sendNotify(Uri uri) {
		String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
		if(notify == null || "true".equals(notify)){
			getContext().getContentResolver().notifyChange(uri, null);
		}
	}

	@Override
	public String getType(Uri uri) {
		SqlArguments args = new SqlArguments(uri, null, null);
		if(!TextUtils.isEmpty(args.where)){
			return "vnd.android.cursor.dir/" + args.table;
		}else{
			return "vnd.android.cursor.item/" + args.table;
		}
	}

	@Override
	public int bulkInsert(Uri uri, ContentValues[] values) {
		// TODO Auto-generated method stub
		return super.bulkInsert(uri, values);
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SqlArguments args = new SqlArguments(uri);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		final long rowId = db.insert(args.table, null, values);
		if(rowId <= 0){
			return null;
		}
		uri = ContentUris.withAppendedId(uri, rowId);
		sendNotify(uri);
		return uri;
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(args.table);
		
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
		result.setNotificationUri(getContext().getContentResolver(), uri);
		return result;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SqlArguments args = new SqlArguments(uri,selection,selectionArgs);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = db.update(args.table, values, args.where, args.args);
		if(count > 0){
			sendNotify(uri);
		}
		return count;
	}

}
